package com.mineoj.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mineoj.annotation.AuthCheck;
import com.mineoj.common.BaseResponse;
import com.mineoj.common.DeleteRequest;
import com.mineoj.common.ErrorCode;
import com.mineoj.common.ResultUtils;
import com.mineoj.constant.UserConstant;
import com.mineoj.exception.BusinessException;
import com.mineoj.exception.ThrowUtils;
import com.mineoj.model.dto.competition.CompetitionAddRequest;
import com.mineoj.model.dto.competition.CompetitionEditRequest;
import com.mineoj.model.dto.competition.CompetitionQueryRequest;
import com.mineoj.model.entity.Competition;
import com.mineoj.model.entity.User;
import com.mineoj.model.vo.CompetitionVO;
import com.mineoj.service.CompetitionService;
import com.mineoj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 帖子接口
 *
 
 */
@RestController
@RequestMapping("/competition")
@Slf4j
public class CompetitionController {

    @Resource
    private CompetitionService competitionService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param competitionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addCompetition(@RequestBody CompetitionAddRequest competitionAddRequest, HttpServletRequest request) {
        if (competitionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = new Competition();
        BeanUtils.copyProperties(competitionAddRequest, competition);

        // 将开始时间和结束时间，从字符串转换为 Date 对象
        String beginTimeStr = competitionAddRequest.getBeginTime();
        String endTimeStr = competitionAddRequest.getEndTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date beginTime = null;
        Date endTime = null;
        try {
            beginTime = sdf.parse(beginTimeStr);
            endTime = sdf.parse(endTimeStr);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "时间格式错误");
        }
        competition.setBeginTime(beginTime);
        competition.setEndTime(endTime);

//        System.out.println(competition);

        competitionService.validCompetition(competition, true);
        User loginUser = userService.getLoginUser(request);
        competition.setUserId(loginUser.getId());
        competition.setJoinNum(0);
        competition.setQuestionNum(0);
        boolean result = competitionService.save(competition);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newCompetitionId = competition.getId();
        return ResultUtils.success(newCompetitionId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteCompetition(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Competition oldCompetition = competitionService.getById(id);
        ThrowUtils.throwIf(oldCompetition == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldCompetition.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = competitionService.removeById(id);
        return ResultUtils.success(b);
    }



    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CompetitionVO> getCompetitionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = competitionService.getById(id);
        if (competition == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(competitionService.getCompetitionVO(competition, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param competitionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CompetitionVO>> listCompetitionVOByPage(@RequestBody CompetitionQueryRequest competitionQueryRequest,
            HttpServletRequest request) {
        long current = competitionQueryRequest.getCurrent();
        long size = competitionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Competition> competitionPage = competitionService.page(new Page<>(current, size),
                competitionService.getQueryWrapper(competitionQueryRequest));
        return ResultUtils.success(competitionService.getCompetitionVOPage(competitionPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param competitionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<CompetitionVO>> listMyCompetitionVOByPage(@RequestBody CompetitionQueryRequest competitionQueryRequest,
            HttpServletRequest request) {
        if (competitionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        competitionQueryRequest.setUserId(loginUser.getId());
        long current = competitionQueryRequest.getCurrent();
        long size = competitionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Competition> competitionPage = competitionService.page(new Page<>(current, size),
                competitionService.getQueryWrapper(competitionQueryRequest));
        return ResultUtils.success(competitionService.getCompetitionVOPage(competitionPage, request));
    }


    /**
     * 编辑（用户）
     *
     * @param competitionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editCompetition(@RequestBody CompetitionEditRequest competitionEditRequest, HttpServletRequest request) {
        if (competitionEditRequest == null || competitionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = new Competition();
        BeanUtils.copyProperties(competitionEditRequest, competition);

        // 参数校验
        competitionService.validCompetition(competition, false);
        User loginUser = userService.getLoginUser(request);
        long id = competitionEditRequest.getId();
        // 判断是否存在
        Competition oldCompetition = competitionService.getById(id);
        ThrowUtils.throwIf(oldCompetition == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldCompetition.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = competitionService.updateById(competition);
        return ResultUtils.success(result);
    }

}
